using MicroMsg.Common.Utils;
using MicroMsg.Manager;
using MicroMsg.Storage;
using System;
using System.Collections.Generic;
namespace MicroMsg.Plugin
{
	public class PluginLoader
	{
		private const string TAG = "PluginLoader";
		public static void scanAvailablePluginList()
		{
			Profiler.setPoint("LoadPluginStart");
			PluginManager.reset();
			ExternPluginList externPluginList = StorageXml.loadResObject<ExternPluginList>(new Uri("Source/Plugin/PluginManifest.xml", 2));
			if (externPluginList == null)
			{
				return;
			}
			using (List<string>.Enumerator enumerator = externPluginList.pluginClassName.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					string current = enumerator.get_Current();
					PluginLoader.preLoadPlugin(current);
					Profiler.setPoint("plugin." + current);
				}
			}
		}
		public static bool preLoadPlugin(string className)
		{
			string text = "MicroMsg.Plugin." + className + "." + className;
			Type type = Type.GetType(text);
			if (type == null)
			{
				Log.smethod_1("PluginLoader", "Not found class, name =  " + text);
				return false;
			}
			Type typeFromHandle = typeof(PluginBase);
			if (!type.IsSubclassOf(typeFromHandle))
			{
				Log.smethod_1("PluginLoader", "Not a plugin class, name = " + text);
				return false;
			}
			PluginBase pluginBase = Activator.CreateInstance(type) as PluginBase;
			if (pluginBase == null)
			{
				Log.smethod_1("PluginLoader", "Failed to create instance, name = " + text);
				return false;
			}
			if (!pluginBase.mEnabled)
			{
				Log.smethod_1("PluginLoader", "Plugin disabled, name = " + text);
				return false;
			}
			Account curAccount = AccountMgr.getCurAccount();
			if (!PluginMetaStorage.restoreMetaInfo(pluginBase))
			{
				Log.smethod_4("PluginLoader", "First load plugin, name = " + text);
				if (!ExtentCenter.registerPlugin(pluginBase))
				{
					Log.smethod_1("PluginLoader", "Not pass to register plugin, name = " + text);
					return false;
				}
				if (pluginBase.mProtocolPluginFlag != (EPluginFlag)0)
				{
					if ((curAccount.nPluginFlag & (uint)pluginBase.mProtocolPluginFlag) == 0u)
					{
						ExtentCenter.installPlugin(pluginBase, InstallMode.DefaultInstall);
					}
				}
				else
				{
					if (pluginBase.mDefaultInstalled)
					{
						ExtentCenter.installPlugin(pluginBase, InstallMode.DefaultInstall);
					}
				}
			}
			else
			{
				Log.smethod_4("PluginLoader", "Restore plugin completed, name = " + text);
				if (!PluginBase.isValidPlugin(pluginBase))
				{
					Log.smethod_1("PluginLoader", "Ignored invalid plugin , name = " + text);
					return false;
				}
				ExtentCenter.initializePlugin(pluginBase);
				ExtentCenter.syncPluginInstall(pluginBase, curAccount.nPluginFlag);
			}
			PluginManager.addPlugin(pluginBase);
			return true;
		}
	}
}
